const userService = require('../services/userService');
const { successResponse } = require('../utils/errorResponse');
const { generateToken } = require('../utils/jwtUtils');

const userController = {
  register: async (req, res, next) => {
    const user = req.body;
    try {
      // 注册用户
      const result = await userService.register(user);
      successResponse(res, result)
    } catch (err) {
      next(err);
    }
  },

  login: async (req, res, next) => {
    const user = req.body;
    try {
      const result = await userService.login(user);
      const token = generateToken(result.id); // 生成token
      successResponse(res, { token, ...result })
    } catch (err) {
      next(err);
    }
  },

  // 获取用户信息
  getUserById: async (req, res, next) => {
    try {
      const { id } = req.params;
      const user = await userService.getUserById(id);
      successResponse(res, user)
    } catch (err) {
      next(err);
    }
  },

  updateUser: async (req, res, next) => {
    const user = req.body;
    try {
      // 更新用户
      const result = await userService.updateUser(user);
      successResponse(res, result)
    } catch (err) {
      next(err);
    }
  },

  deleteUser: async (req, res, next) => {
    const user = req.body;
    try {
      // 删除用户
      const result = await userService.deleteUser(user);
      successResponse(res, result)
    } catch (err) {
      next(err);
    }
  },

  getUserList: async (req, res, next) => {
    try {
      const users = await userService.getUserList();
      successResponse(res, users)
    } catch (error) {
      next(error);
    }
  }
}

module.exports = userController